<?php

namespace helper\cloud;

use TencentCloud\Common\Credential;
use TencentCloud\Common\Profile\ClientProfile;
use TencentCloud\Common\Profile\HttpProfile;

class Tencent
{

    private $option;
    private $cred;

    /**
     * 实例化
     * @param $options
     */
    public function __construct($options)
    {
        if (is_array($options)) {
            $this->option = $options;
        } else {
            $this->option     = config('cloud.'.$options.'.config.tencent');
        }
        $this->cred = new Credential($this->option['accessId'], $this->option['accessSecret']);
    }

    /**
     * 获取配置参数
     * @param string $name
     * @return array|mixed
     */
    public function getOption($name = '')
    {
        if (empty($name)) return $this->option;
        return $this->option[$name];
    }

    /**
     * 获取对应产品接口
     * @param $product
     * @param $version
     * @return mixed
     */
    public function getInterface($product, $version)
    {
        $httpProfile = new HttpProfile();
        $httpProfile->setEndpoint(strtolower($product) . ".tencentcloudapi.com");
        $clientProfile = new ClientProfile();
        $clientProfile->setHttpProfile($httpProfile);
        $productClass = "\\TencentCloud\\{$product}\\{$version}\\{$product}Client";
        $regionId     = $this->option['regionId'] ?? '';
        return new $productClass($this->cred, $regionId, $clientProfile);
    }

    /**
     * 直接执行指定方法
     * @param $product
     * @param $version
     * @param $fun
     * @param array $options
     * @return mixed
     */
    public function execFun($product, $version, $fun, $options = [])
    {
        $handler  = $this->getInterface($product, $version);
        $reqClass = "\\TencentCloud\\{$product}\\{$version}\\Models\\{$fun}Request";
        $req      = new $reqClass();
        $req->fromJsonString(json_encode($options, JSON_UNESCAPED_UNICODE));
        $ret = $handler->$fun($req);
        return json_decode($ret->toJsonString(), true);
    }

}